import db
import pymysql
from tc import send_push
from multiprocessing.dummy import Pool

def get_subscribers(db_conn):
  db_c = db_conn.cursor(cursor=pymysql.cursors.DictCursor)
  db_c.execute('SELECT * FROM `subscriptions` WHERE `activated`=1 AND UNIX_TIMESTAMP()<`expire_time`')
  records = db_c.fetchall()
  db_c.close()
  return records

def broadcast_push(targets, subject, body):
  p = Pool(4)
  for t in targets:
    p.apply_async(send_push, ('UBR Job Watch Service', subject, body, t))
  p.close()
  p.join()
  print('BROADCAST COMPLETE! ')

def broadcast_push_to_subscribers(subject, body):
  conn = db.get_conn()
  subs = []
  for v in get_subscribers(conn):
    subs.append(v['target'])
  conn.close()
  print('[!] SUBSCRIBERS AMOUNT: ' + str(len(subs)))
  broadcast_push(subs, subject, body)

def test():
  c = db.get_conn()
  s = get_subscribers(c)
  c.close()
  return s

if __name__ == '__main__':
  x = test()
  for v in x:
    print('TARGET: ' + v['target'])
